import json
import requests
import unittest


class PublicNry(unittest.TestCase):
    env = 'test'
    token_file = 'C:\Sessionid&Token.json'
    config = {
        'test': {'url': 'https://nry-test.b2bwings.com', 'phone': 15900000000, 'pw': '123456'}
        }
    pw = config[env]['pw']
    url = config[env]['url']
    phone = config[env]['phone']

    def get_token(self, phone, pw,  new_token):
        '''获取token,new_token是否获取新的token'''
        token_key = f'{self.url, phone}'
        head = {'Content-Type': 'application/json'}
        if new_token:
            full_url = self.url + '/api/core/v1/login/authentication'
            data = {"account": phone, "password": pw, "check": False,"channel": 1}
            res = requests.post(full_url, json=data, headers=head, verify=False).json()
            token = res['data']['token']
            #每次获取新token时都进行更新保存（先读取json用于追加或更新，如果json不存在或内容非json格式则赋值为{}）
            try:
                with open(self.token_file, 'r', encoding='utf-8') as file:
                    json_data = json.load(file)
            except (FileNotFoundError, json.JSONDecodeError):
                json_data = {}
            with open(self.token_file, 'w', encoding='utf-8') as file:
                json_data.update({token_key: token})
                json.dump(json_data, file, indent=4, ensure_ascii=False)
        else:
            try:
                with open(self.token_file, 'r', encoding='utf-8') as file:
                    token = json.load(file)[token_key]
            except:
                token = self.get_token(phone, pw, new_token=True)
        return token

    def post(self, api, data, phone=phone, pw=pw, new_token=False ):
        for i in range(2):
            head = {
                    'Content-Type': 'application/json',
                    'token': self.get_token(phone, pw, new_token)
                   }
            res = requests.post(
                url = self.url + api,
                json = data,
                headers = head,
                verify = False
            ).json()
            if res['message'] == '需要登录!':
                self.get_token(phone, pw, new_token=True)
            else:
                break
        self.assertEqual(res['message'], '操作成功', f'环境{self.env},接口{api},传参{data}')
        return res